﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DauGiaApp.Models;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using Microsoft.Web.Helpers;
namespace DauGiaApp.Controllers
{
    public class SanPhamController : Controller
    {
        //
        // GET: /SanPham/
        
        public DauGiaEntities data = new DauGiaEntities();
        public bool IsRole(TaiKhoan tk, string actionName)
        {

            PhanQuyen pq = (from dspq in data.PhanQuyens where dspq.TenQuyen == actionName select dspq).SingleOrDefault();
            ChiTietPhanQuyen ctpq = (from ctpqs in data.ChiTietPhanQuyens where (ctpqs.MaLoaiTaiKhoan == tk.MaLoaiTaiKhoan) && (ctpqs.MaPhanQuyen == pq.MaPhanQuyen) select ctpqs).Single();
            if (ctpq != null)
                return true;
            return false;
        }
        
        public ActionResult Index()
        {
            
            return View();
        }

        public ActionResult DanhSach()
        {
            var dssp  = data.SanPhams.OrderByDescending(or=>or.NgayDang).Take(SanPham.takeView);
            ViewBag.TongSanPham = data.SanPhams.Count();
            return View(dssp);
        }

        public ActionResult DanhSachPage(int from)
        {
            ViewBag.TongSanPham = data.SanPhams.Count();
            var sauKhiSkip = data
                             .SanPhams
                             .OrderByDescending(or => or.NgayDang)
                             .Skip(from * SanPham.takeView);

            var dssp = sauKhiSkip.Take(SanPham.takeView);
            return View(dssp);
        }

        public ActionResult ChiTiet(string id)
        {

            int masp = Int32.Parse(id);
            var query = from sp in data.SanPhams
                        where sp.MaSanPham == masp
                        select sp;
            
            return View(query.ToList().ElementAt(0));

        }

        public ActionResult DangSanPham()
        {
            ViewBag.MaLoaiSanPham = new SelectList(data.LoaiSanPhams, "MaLoaiSanPham", "TenLoaiSanPham");
            return View();
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult DangSanPham(SanPham sp)
        {
            TaiKhoan curTK = Session["user"] as TaiKhoan;
            if (curTK != null)
            {
                try
                {
                    if (IsRole(curTK, "DangSanPham"))
                    {
                        try
                        {
                            // thay doi sau => nguoi dang
                            TaiKhoan tk = (TaiKhoan)Session["user"];
                            sp.MaTaiKhoan = tk.MaTaiKhoan;
                            sp.NgayDang = DateTime.Now;

                            // cho dau gia  
                            sp.MaTinhTrangSanPham = 1;

                            List<int> dsUpload = (List<int>)Session["AnhUpload"];

                            foreach (int maanh in dsUpload)
                            {
                                SanPham_Multimedia spm = new SanPham_Multimedia();
                                spm.MaMT = maanh;
                                sp.SanPham_Multimedia.Add(spm);
                            }
                            int maadd = 0;
                            if (sp.MaAnhDaiDien != null)
                                maadd = (int)sp.MaAnhDaiDien;
                            sp.MaAnhDaiDien = dsUpload.ElementAt(maadd);

                            data.SanPhams.AddObject(sp);
                            data.SaveChanges();
                            Session["AnhUpload"] = null;
                            ViewBag.MaLoaiSanPham = new SelectList(data.LoaiSanPhams, "MaLoaiSanPham", "TenLoaiSanPham");
                            return View();
                        }
                        catch (Exception)
                        {
                            return View();
                        }
                    }
                    else
                    {
                        // Hoac thong bao thui.
                        return RedirectToAction("Alert", "Home");
                    }
                }
                catch
                {
                    //Response.Write("<script>alert('bạn không có quyền');</script>");
                    return RedirectToAction("Alert", "Home");
                }



            }
            else
            {
                return RedirectToAction("DangNhap", "TaiKhoan");
            }
            return RedirectToAction("Index", "Home");

           
            
        }


        [HttpPost]
        public ActionResult FileUpload(string qqfile)
        {
            var path = HttpContext.Server.MapPath("../Uploads");
            var file = string.Empty;

            try
            {
                var stream = Request.InputStream;
                if (String.IsNullOrEmpty(Request["qqfile"]))
                {
                    // IE
                    HttpPostedFileBase postedFile = Request.Files[0];
                    stream = postedFile.InputStream;
                    file = Path.Combine(path, System.IO.Path.GetFileName(Request.Files[0].FileName));
                }
                else
                {
                    //Webkit, Mozilla
                    file = Path.Combine(path,
                                        qqfile);
                }

                var buffer = new byte[stream.Length];
                stream.Read(buffer, 0, buffer.Length);
                
                System.IO.File.WriteAllBytes(file, buffer);
                Multimedia mul = new Multimedia();
                mul.TenMT = qqfile;
                mul.LinkURL = qqfile;
                mul.MaLoaiMT = 1;
                data.Multimedias.AddObject(mul);
                data.SaveChanges();
                if (Session["AnhUpload"] == null)
                {
                    List<int> dsUpload = new List<int>();
                    dsUpload.Add(mul.MaMT);
                    Session["AnhUpload"] = dsUpload;
                }
                else
                {
                    List<int> dsUpload = (List<int>)Session["AnhUpload"];
                    dsUpload.Add(mul.MaMT);
                    Session["AnhUpload"] = dsUpload;
                }
                
            }

            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message },JsonRequestBehavior.AllowGet);
            }

            return Json(new { success = true },JsonRequestBehavior.AllowGet);
        }

        public ActionResult LoaiSanPham(string tenloai)
        {
            List<SanPham> dssanpham = (from sp in data.SanPhams
                                       where (sp.LoaiSanPham.TenLoaiSanPham == tenloai)
                                       select sp).ToList();
            return View(dssanpham);
        }
    }
}
